package match

import (
	"sanguo/cluster"
	"sanguo/node/node_team"
	"sanguo/node/node_team/com"
	"sanguo/node/node_team/team"
	ss_msg "sanguo/protocol/ss/message"

	"github.com/golang/protobuf/proto"
	"github.com/sniperHW/kendynet"
)

const (
	agree    = 1
	disAgree = 2
)

func CheckReply(_team *team.Team) {
	_fight := _team.Fight
	if _fight.AgreeCount == int32(_team.GetRoleCount()) {
		_team.Fight = nil
		//匹配
		nodeId, err := com.MatchGenID()
		if err != nil {
			node_team.Infoln(err)
			return
		}

		obj := &Object{
			NodeID: nodeId,
			Size:   int32(_team.GetRoleCount()),
			TeamID: _team.TeamID,
			Roles:  map[uint64]*RoleInfo{},
		}

		for _, r := range _team.GetRoles() {
			obj.Roles[r.RoleID] = &RoleInfo{
				UserID:      r.UserID,
				RoleID:      r.RoleID,
				Game:        r.Game,
				BattleAttrs: map[int32]int32{},
				Skills:      []*Skill{},
			}
		}

		//拉取角色信息
		obj.getRoleInfo()

	}

	if _fight.AgreeCount+_fight.DisAgreeCount == int32(len(_fight.RoleReply)) {
		_team.Status = com.TeamStatus_Safe
		_team.Fight = nil
	}
}

func OnFightInvite(session kendynet.StreamSession, msg proto.Message) {
	arg := msg.(*ss_msg.FightInvite)
	node_team.Debugln("OnCall FightInvite", arg)

	_team := team.TeamMgr.GetTeam(arg.GetTeamID())
	if _team != nil {

		_fight := _team.Fight
		if _fight != nil && _fight.RoleReply[arg.GetRoleID()] == 0 {
			if arg.GetReply() == agree {
				_fight.AgreeCount++
				_fight.RoleReply[arg.GetRoleID()] = agree

			} else if arg.GetReply() == disAgree {
				_fight.DisAgreeCount++
				_fight.RoleReply[arg.GetRoleID()] = agree

			}
			team.UpdateFightInvite(_team)
			CheckReply(_team)
		}

	}

}

func init() {
	cluster.Register(&ss_msg.FightInvite{}, func(session kendynet.StreamSession, msg proto.Message) {
		OnFightInvite(session, msg)
	})
}
